﻿using System.IO;
using Microsoft.Win32;
using Oxage.Converters;

namespace Oxage.Models
{
	public partial class DocumentViewModel : DocumentModel
	{
		#region Public properties
		/// <summary>
		/// Gets or sets a full path to the file that has been last used for loading or saving.
		/// </summary>
		public string LastUsedFileName
		{
			get
			{
				return this.lastUsedFileName;
			}
			set
			{
				if (this.lastUsedFileName != value)
				{
					this.lastUsedFileName = value;
					OnPropertyChanged("LastUsedFileName");
					OnPropertyChanged("CanSaveWithoutDialog");
				}
			}
		}
		private string lastUsedFileName;

		/// <summary>
		/// Gets a value indicating whether user can save content directly without opening file dialog.
		/// </summary>
		public bool CanSaveWithoutDialog
		{
			get
			{
				return !string.IsNullOrEmpty(this.LastUsedFileName);
			}
		}

		/// <summary>
		/// Gets or sets a value indicating whether content has changed.
		/// </summary>
		public bool HasChanged
		{
			get
			{
				return this.hasChanged;
			}
			set
			{
				if (this.hasChanged != value)
				{
					this.hasChanged = value;
					OnPropertyChanged("HasChanged");
				}
			}
		}
		private bool hasChanged;
		#endregion

		#region Public methods
		public void New()
		{
			this.Content = "";
			this.LastUsedFileName = null;
			this.HasChanged = false;
		}

		public void Open(string path)
		{
			this.Content = File.ReadAllText(path);
			this.LastUsedFileName = path;
			this.HasChanged = false;
		}

		public void Save(string path)
		{
			File.WriteAllText(path, this.Content);
			this.LastUsedFileName = path;
			this.HasChanged = false;
		}

		public void ImportDialog()
		{
			var dialog = new OpenFileDialog();
			dialog.Filter = "SVG (*.svg)|*.svg" + "|" + "XAML (*.xaml)|*.xaml";

			if (dialog.ShowDialog() == true)
			{
				string svg = File.ReadAllText(dialog.FileName);
				var converter = new SVGConverter();
				this.Content = converter.SVGToGCode(svg);
				this.LastUsedFileName = null;
			}
		}

		public void ExportDialog()
		{
			var dialog = new SaveFileDialog();
			dialog.Filter = "SVG (*.svg)|*.svg" + "|" + "XAML (*.xaml)|*.xaml";

			if (dialog.ShowDialog() == true)
			{
				File.WriteAllText(dialog.FileName, this.Content);
				this.LastUsedFileName = dialog.FileName;
			}
		}
		#endregion
	}
}
